package com.crr.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogAspect {
    @Pointcut("execution(void *IceBox(int))")
    public void p1() {
    }

    @Before("p1()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        String method = joinPoint.getSignature().getName();
        if ("buyIceBox".equals(method)) {
            System.out.println("欢迎购买");
        }
        if ("storeIceBox".equals(method)) {
            if ((int) args[0] < 0) {
                System.out.println("库存不足");
            }

        }
    }

    @AfterReturning("p1()")
    public void afterReturning(JoinPoint joinPoint) {
        String method = joinPoint.getSignature().getName();
        if ("buyIceBox".equals(method)) {
            System.out.println("恭喜购买成功");
        }
    }

    @AfterThrowing(pointcut = "p1()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, OutOfNumberException e) {
        String method = joinPoint.getSignature().getName();
        System.out.println("执行方法发生异常  " + e.getMessage());
    }

    @Around("p1()")
    public Object aroundTest(ProceedingJoinPoint pjp) {

        String method = pjp.getSignature().getName();
        long begin = System.currentTimeMillis();
        System.out.println(method + "方法开始执行,计时开始");
        try {
            return pjp.proceed();

        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {

            long end = System.currentTimeMillis();
            System.out.println(method + "方法执行完毕，用时" + (end - begin) + "毫秒");
        }
    }

}
